import axios from 'axios';
import type { AxiosInstance } from 'axios';

const isDev = process.env.NODE_ENV == 'development';

import router from '@/router';

// 创建连接对象
const request: AxiosInstance = axios.create({
    baseURL: isDev ? 'http://10.31.155.23:3100' : 'http://10.31.155.23:3100', // 修改端口为 3100
    timeout: 60000
});

// 添加请求拦截器
request.interceptors.request.use(function (config) {
    
    return config;

}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {

    return response;
}, function (error) {
    return Promise.reject(error);
});

interface isConfig {
    url: string;
    method?: string;
    data?: any;
    headers?: any;
}

// 自定义各种请求数据的方法
export default function ajax(config: isConfig) {
    const { url = '', method = 'get', data = {}, headers = {} } = config;

    switch (method.toUpperCase()) {
        case 'GET':
            return request.get(url, { params: data });
        case 'POST':
            if (headers['content-type'] === 'application/x-www-form-urlencoded') {
                const obj = new URLSearchParams();
                for (const key in data) {
                    obj.append(key, data[key]);
                }
                return request.post(url, obj, { headers });
            }
            if (headers['content-type'] === 'multipart/form-data') {
                const obj = new FormData();
                for (const key in data) {
                    obj.append(key, data[key]);
                }
                return request.post(url, obj, { headers });
            }
            // 直接发送 JSON 数据
            return request.post(url, data);

        case 'DELETE':
            return request.delete(url, { data });
        case 'PUT':
            return request.put(url, data);
        case 'PATCH':
            return request.patch(url, data);
        default:
            return request.request(config);
    }
}
